﻿using AyuBookmark.Common.Models;
using AyuBookmark.WinForm.Commands;
using AyuBookmark.WinForm.Pipes;
using System;
using System.ComponentModel;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AyuBookmark.WinForm.ViewModels
{
    /// <summary>
    /// 书签编辑/查看的ViewModel
    /// </summary>
    public class BookmarkViewModel : INotifyPropertyChanged
    {
        private readonly PipeClient _pipeClient;
        private Bookmark _bookmark;
        private bool _isEditMode;

        public event PropertyChangedEventHandler PropertyChanged;

        public BookmarkViewModel(Bookmark bookmark = null, bool isEditMode = false)
        {
            _pipeClient = new PipeClient("AyuBookmarkPipe");
            _bookmark = bookmark ?? new Bookmark { CreatedTime = DateTime.Now };
            _isEditMode = isEditMode;

            InitializeCommands();
        }

        #region 数据绑定属性
        public int Id
        {
            get => _bookmark.Id;
            set
            {
                _bookmark.Id = value;
                OnPropertyChanged(nameof(Id));
            }
        }

        public string Url
        {
            get => _bookmark.Url;
            set
            {
                _bookmark.Url = value;
                OnPropertyChanged(nameof(Url));
                if (string.IsNullOrEmpty(Title))
                {
                    Title = GenerateTitleFromUrl(value);
                }
            }
        }

        public string Title
        {
            get => _bookmark.Title;
            set
            {
                _bookmark.Title = value;
                OnPropertyChanged(nameof(Title));
            }
        }

        public string Description
        {
            get => _bookmark.Description;
            set
            {
                _bookmark.Description = value;
                OnPropertyChanged(nameof(Description));
            }
        }

        public Category Category
        {
            get => _bookmark.Category;
            set
            {
                _bookmark.Category = value;
                OnPropertyChanged(nameof(Category));
            }
        }

        public DateTime CreatedTime
        {
            get => _bookmark.CreatedTime;
            set
            {
                _bookmark.CreatedTime = value;
                OnPropertyChanged(nameof(CreatedTime));
            }
        }

        public bool IsEditMode
        {
            get => _isEditMode;
            set
            {
                _isEditMode = value;
                OnPropertyChanged(nameof(IsEditMode));
                OnPropertyChanged(nameof(WindowTitle));
            }
        }

        public string WindowTitle => IsEditMode ? "编辑书签" : "查看书签";
        #endregion

        #region 命令
        public IRelayCommand SaveCommand { get; private set; }
        public IRelayCommand CancelCommand { get; private set; }
        public IRelayCommand OpenUrlCommand { get; private set; }
        #endregion

        #region 公共方法
        /// <summary>
        /// 获取当前书签的深拷贝
        /// </summary>
        public Bookmark GetBookmark()
        {
            return new Bookmark
            {
                Id = _bookmark.Id,
                Url = _bookmark.Url,
                Title = _bookmark.Title,
                Description = _bookmark.Description,
                Category = _bookmark.Category,
                CreatedTime = _bookmark.CreatedTime
            };
        }
        #endregion

        #region 私有方法
        private void InitializeCommands()
        {
            SaveCommand = new RelayCommand(async _ => await SaveAsync());
            CancelCommand = new RelayCommand(_ => OnCancelRequested());
            OpenUrlCommand = new RelayCommand(_ => OpenUrl(), _ => !string.IsNullOrEmpty(Url));
        }

        private async Task SaveAsync()
        {
            if (string.IsNullOrWhiteSpace(Url))
            {
                MessageBox.Show("URL不能为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            try
            {
                var command = IsEditMode ? "UpdateBookmark" : "AddBookmark";
                var response = await _pipeClient.SendMessageAsync(
                    JsonSerializer.Serialize(new
                    {
                        Command = command,
                        Data = GetBookmark()
                    }));

                if (response?.Contains("success", StringComparison.OrdinalIgnoreCase) == true)
                {
                    MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    OnSaveCompleted();
                }
                else
                {
                    MessageBox.Show("保存失败: " + response, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void OpenUrl()
        {
            try
            {
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                {
                    FileName = Url,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开链接失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GenerateTitleFromUrl(string url)
        {
            try
            {
                var uri = new Uri(url);
                return uri.Host.Replace("www.", "").Replace(".com", "");
            }
            catch
            {
                return "未命名书签";
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion

        #region 事件
        public event EventHandler SaveCompleted;
        public event EventHandler CancelRequested;

        protected virtual void OnSaveCompleted()
        {
            SaveCompleted?.Invoke(this, EventArgs.Empty);
        }

        protected virtual void OnCancelRequested()
        {
            CancelRequested?.Invoke(this, EventArgs.Empty);
        }
        #endregion
    }
}